package com.xiaohuihui.springbootsecurity.service.impl;

import com.xiaohuihui.springbootsecurity.domain.ApiResult;
import com.xiaohuihui.springbootsecurity.domain.LoginUser;
import com.xiaohuihui.springbootsecurity.domain.User;
import com.xiaohuihui.springbootsecurity.service.LoginService;
import com.xiaohuihui.springbootsecurity.utils.JwtUtil;
import com.xiaohuihui.springbootsecurity.utils.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisService redisService;

    @Override
    public ApiResult<Object> login(User user) {
        log.info("login start");
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUser().getId().toString());
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("user", loginUser.getUser());
        redisService.setBean("login:"+loginUser.getUser().getId(),loginUser);
        return ApiResult.ok(map);


    }

    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        redisService.delete("login:"+id);
    }
}
